package com.foreverwin.mes.lims.controller;

import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BaseException;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.model.InspectProjectDetail;
import com.foreverwin.mes.meapi.model.DcGroup;
import com.foreverwin.mes.meapi.model.DcParameter;
import com.foreverwin.mes.meapi.service.DcGroupService;
import com.foreverwin.mes.meapi.service.DcParameterService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.InspectProjectDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Levy
 * @since 2020-02-19
 */
@Controller
@RequestMapping("/inspectProjectDetails")
public class InspectProjectDetailController {
    private final Logger logger = LoggerFactory.getLogger(InspectProjectDetailController.class);

    @Autowired
    public InspectProjectDetailService inspectProjectDetailService;

    @Autowired
    private DcGroupService dcGroupService;
    @Autowired
    private DcParameterService dcParameterService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getInspectProjectDetailById(@PathVariable String id) {
        InspectProjectDetail result;
        try {
            result = inspectProjectDetailService.selectById(id);
        } catch (Exception e) {
            logger.error("getInspectProjectDetailById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getInspectProjectDetailList(InspectProjectDetail inspectProjectDetail){
        List<InspectProjectDetail> result;
        try {
            EntityWrapper<InspectProjectDetail> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectProjectDetail);
            result = inspectProjectDetailService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectProjectDetailList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getInspectProjectDetailPageList")
    public AjaxResult getInspectProjectDetailPageList(FrontPage<InspectProjectDetail> frontPage, InspectProjectDetail inspectProjectDetail){
        Page result;
        try {
            String site = CommonMethods.getSite();
            //inspectProjectDetail.setSite(site);
            EntityWrapper<InspectProjectDetail> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(inspectProjectDetail);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("item", frontPage.getGlobalQuery())
                    .or().like("projectBo", frontPage.getGlobalQuery())
                    .or().like("itemDesc", frontPage.getGlobalQuery())
                    .or().like("dataType", frontPage.getGlobalQuery())
                    .or().like("checkStandard", frontPage.getGlobalQuery())
                    .or().like("standardValue", frontPage.getGlobalQuery())
                    .or().like("lowerLimit", frontPage.getGlobalQuery())
                    .or().like("upperLimit", frontPage.getGlobalQuery())
                    .or().like("sampleQty", frontPage.getGlobalQuery())
                    .or().like("arrayName", frontPage.getGlobalQuery())
                    .or().like("sourceData", frontPage.getGlobalQuery())
                    .or().like("report", frontPage.getGlobalQuery())
        ;
            }
            result = inspectProjectDetailService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getInspectProjectDetailPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param inspectProjectDetail  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult inspectProjectDetailSave(@RequestBody InspectProjectDetail inspectProjectDetail) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        int count;
        try {
            count = inspectProjectDetailService.insertOrUpdate(inspectProjectDetail) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectProjectDetailSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : inspectProjectDetail);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult inspectProjectDetailDelete(@PathVariable("id") String id){
        int count;
        try {
            count = inspectProjectDetailService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectProjectDetailDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = inspectProjectDetailService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("inspectProjectDetailBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    @ResponseBody
    @GetMapping(value = "/getDcGroup")
    public AjaxResult getInspectTask( String dcGroupBo ) {

        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        List<InspectProjectDetail> inspectProjectDetails= new ArrayList<InspectProjectDetail>();

        try {

           DcGroup dcGroup =  dcGroupService.selectById( dcGroupBo );
           if ( dcGroup == null ){
               throw BusinessException.build("数据收集组【"+ dcGroupBo.split( "," )[1] +"】不存在");
           }
           Map param  = new HashMap();
           param.put( "DC_GROUP_BO", dcGroupBo );
           List<DcParameter> dcParameters =  dcParameterService.selectByMap( param );
           if ( !dcParameters.isEmpty() ){
               for ( DcParameter dcParameter : dcParameters  ){
                   InspectProjectDetail inspectProjectDetail = new InspectProjectDetail();

                   inspectProjectDetail.setItem( dcParameter.getParameterName() );
                   inspectProjectDetail.setItemDesc( dcParameter.getDescription() );
                   inspectProjectDetail.setDataType( dcParameter.getDataType() );
                   inspectProjectDetail.setReport("Y");

                   Double max = dcParameter.getMaxValue();
                   Double min = dcParameter.getMinValue();

                   inspectProjectDetails.add( inspectProjectDetail );
               }
           }

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }

        return AjaxResult.success( inspectProjectDetails );
    }
}